package controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.csource.common.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import common.ExtensionIcon;
import common.FileManager;
import pojo.EssayFile;
import pojo.Manager;
import pojo.User;
import pojo.FastDFSFile;
import service.UserServiceI;

@RequestMapping("fileControll")
@Controller
public class FileManagerController {

	/**
	 * 
	 * @Title: uploadFile   
	 * @Description: 上传发表文章的文件的控制器
	 * @param: @param mFile
	 * @param: @param request
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	private List<EssayFile> EssayFile=new ArrayList<EssayFile>();
	@RequestMapping("uploadFile")
	@ResponseBody
	public  String uploadFile(@RequestParam("file")MultipartFile mFile,HttpServletRequest request,HttpSession session) throws Exception {
		User user=(User) request.getSession().getAttribute("user");
		String userName=null;
		if(user!=null) {
			 userName=user.getUserName() ;
		}else {
			userName="undefined";
		}
	    String ext = mFile.getOriginalFilename().substring(mFile.getOriginalFilename().lastIndexOf(".")+1);
	    FastDFSFile file = new FastDFSFile(mFile.getBytes(),ext);
	    NameValuePair[] meta_list = new NameValuePair[4];
	    meta_list[0] = new NameValuePair("fileName", mFile.getOriginalFilename());
	    meta_list[1] = new NameValuePair("fileLength", String.valueOf(mFile.getSize()));
	    meta_list[2] = new NameValuePair("fileExt", ext);
	    meta_list[3] = new NameValuePair("fileAuthor", "Believe");
	    try {
	    	FileManager fileManager=new FileManager("fdfs_client.conf");
		    String filePath = fileManager.upload(file,meta_list);
            /******************************将上传的图片路径保存到session中，方便更新表以及取消发布的时候删除服务器的文件******************************************************/
	    	List<EssayFile> Temp=null;
	    	if(session.getAttribute("EssayFile")!=null) {
	    		Temp=(List<EssayFile>) session.getAttribute("EssayFile");//上传图片。并将路径保存到session中
	    	}else {
	    		Temp=new ArrayList<EssayFile>();
	    	}
			EssayFile essayFile=new EssayFile();
			ExtensionIcon eIcon=new ExtensionIcon();
            essayFile.setFilePath(filePath);
            essayFile.setFileLabel("picture");//设置文件类别为picture，即为图片
            essayFile.setFileName(mFile.getOriginalFilename());
            essayFile.setExt(eIcon.extensionIcon(ext));
            Temp.add(essayFile);
            session.setAttribute("EssayFile", Temp);
           /* System.out.println(session.getAttribute("EssayFile"));*/
            /*****************************返回固定格式的json，否则layui解析失败，显示上传错误****************************************************/
            Map<String,Object> map = new HashMap<String,Object>();
            Map<String,Object> map2 = new HashMap<String,Object>();
            map.put("code",0);//0表示成功，1失败
            map.put("msg","上传成功");//提示消息
            map.put("data",map2);
            map2.put("src",filePath);//图片url
            map2.put("title",userName);
            Gson gson=new Gson();
            String result = gson.toJson(map);
            return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return "";
	}
	
	/**
	 * 
	 * @Title: upAndDownFile   
	 * @Description: TODO(上传可供下载文件)   
	 * @param: @param mFile
	 * @param: @param request
	 * @param: @param session
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("upAndDownFile")
	@ResponseBody
	public  String upAndDownFile(@RequestParam("file")MultipartFile mFile,HttpServletRequest request,HttpSession session) throws Exception {
		User user=(User) request.getSession().getAttribute("user");
		session.setAttribute("EssayFile", EssayFile);
		String userName=null;
		if(user!=null) {
			 userName=user.getUserName() ;
		}else {
			userName="undefined";
		}
	    String ext = mFile.getOriginalFilename().substring(mFile.getOriginalFilename().lastIndexOf(".")+1);
	    FastDFSFile file = new FastDFSFile(mFile.getBytes(),ext);
	    NameValuePair[] meta_list = new NameValuePair[4];
	    meta_list[0] = new NameValuePair("fileName", mFile.getOriginalFilename());
	    meta_list[1] = new NameValuePair("fileLength", String.valueOf(mFile.getSize()));
	    meta_list[2] = new NameValuePair("fileExt", ext);
	    meta_list[3] = new NameValuePair("fileAuthor", "Believe");
	    try {
	    	FileManager fileManager=new FileManager("fdfs_client.conf");
    	    String filePath = fileManager.upload(file,meta_list);
    	    /************************************************************************************/
	    	List<EssayFile> Temp=null;
	    	if(session.getAttribute("EssayFile")!=null) {
	    		Temp=(List<EssayFile>) session.getAttribute("EssayFile");//上传图片。并将路径保存到session中
	    	}else {
	    		Temp=new ArrayList<EssayFile>();
	    	}
			EssayFile essayFile=new EssayFile();
			ExtensionIcon eIcon=new ExtensionIcon();
            essayFile.setFilePath(filePath);
            essayFile.setFileLabel("file");//设置文件类别为file，即提供下载的文件
            essayFile.setFileName(mFile.getOriginalFilename());
            essayFile.setExt(eIcon.extensionIcon(ext));
            Temp.add(essayFile);
            session.setAttribute("EssayFile", Temp);
            /*********************************************************************************/
		    Map<String,Object> map = new HashMap<String,Object>();
            map.put("code",0);//0表示成功，1失败
            map.put("msg","上传成功");//提示消息
            map.put("filepath",filePath);
            Gson gson=new Gson();
            String result = gson.toJson(map);
            return result;
		} catch (Exception e) {
		}
		return ext;
	}
	
	/**
	 * 
	 * @Title: uploadVideo   
	 * @Description: TODO(上传视频)   
	 * @param: @param mFile
	 * @param: @param request
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("uploadVideo")
	@ResponseBody
	public  String uploadVideo(@RequestParam("file")MultipartFile mFile,HttpServletRequest request,HttpSession session) throws Exception {
		User user=(User) request.getSession().getAttribute("user");
		String userName=null;
		if(user!=null) {
			 userName=user.getUserName() ;
		}else {
			userName="undefined";
		}
	    String ext = mFile.getOriginalFilename().substring(mFile.getOriginalFilename().lastIndexOf(".")+1);
	    FastDFSFile file = new FastDFSFile(mFile.getBytes(),ext);
	    NameValuePair[] meta_list = new NameValuePair[4];
	    meta_list[0] = new NameValuePair("fileName", mFile.getOriginalFilename());
	    meta_list[1] = new NameValuePair("fileLength", String.valueOf(mFile.getSize()));
	    meta_list[2] = new NameValuePair("fileExt", ext);
	    meta_list[3] = new NameValuePair("fileAuthor", "Believe");
	    try {
	    	FileManager fileManager=new FileManager("fdfs_client.conf");
		    String filePath = fileManager.upload(file,meta_list);
		    /************************************************************************************/
	    	List<EssayFile> Temp=null;
	    	if(session.getAttribute("EssayFile")!=null) {
	    		Temp=(List<EssayFile>) session.getAttribute("EssayFile");//上传图片。并将路径保存到session中
	    	}else {
	    		Temp=new ArrayList<EssayFile>();
	    	}
			EssayFile essayFile=new EssayFile();
			ExtensionIcon eIcon=new ExtensionIcon();
            essayFile.setFilePath(filePath);
            essayFile.setFileLabel("video");//设置文件类别为video，即为视频
            essayFile.setFileName(mFile.getOriginalFilename());
            essayFile.setExt(eIcon.extensionIcon(ext));
            Temp.add(essayFile);
            session.setAttribute("EssayFile", Temp);
            /*********************************************************************************/
		    Map<String,Object> map = new HashMap<String,Object>();
            map.put("code",0);//0表示成功，1失败
            map.put("msg","上传成功");//提示消息
            map.put("filepath",filePath);
            Gson gson=new Gson();
            String result = gson.toJson(map);
            return result;
		} catch (Exception e) {
		}
		return ext;
	}
	/**
	 * 
	 * 
	 * @Title: uploadheadFile   
	 * @Description:上传头像的控制器
	 * @param: @param mFile
	 * @param: @param request
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@Autowired
	private UserServiceI uServiceI;
	@RequestMapping("uploadheadFile")
	@ResponseBody
	public  String uploadheadFile(@RequestParam("file")MultipartFile mFile,HttpServletRequest request) throws Exception {
		FileManager fileManager=new FileManager("fdfs_client.conf");
	    String ext = mFile.getOriginalFilename().substring(mFile.getOriginalFilename().lastIndexOf(".")+1);
	    FastDFSFile file = new FastDFSFile(mFile.getBytes(),ext);
	    NameValuePair[] meta_list = new NameValuePair[4];
	    meta_list[0] = new NameValuePair("fileName", mFile.getOriginalFilename());
	    meta_list[1] = new NameValuePair("fileLength", String.valueOf(mFile.getSize()));
	    meta_list[2] = new NameValuePair("fileExt", ext);
	    meta_list[3] = new NameValuePair("fileAuthor", "Believe");
	    String filePath = fileManager.upload(file,meta_list);//�ϴ��ļ�
	    if(filePath!=null) {
	    	 /********************更新头像*******************************/
	    	User user=(User) request.getSession().getAttribute("user");
	    	String oldhead=user.getHeadSculpture();
	    	if(oldhead==null||oldhead.equals("")) {//没有旧头像，直接上传
		    	Integer userId=user.getUserId();
		    	User user2=new User();
		    	user2.setUserId(userId);
		    	user2.setHeadSculpture(filePath);
		    	int i=uServiceI.CompleteUserInformation(user2);
		    	if(i>0) {
		    		JsonObject jsonObject=new JsonObject();
		    		jsonObject.addProperty("ecode", "1");
		    		String jb=jsonObject.toString();
		    		return jb;
		    	}else {
		    		JsonObject jsonObject=new JsonObject();
		    		jsonObject.addProperty("ecode", "0");
		    		String jb=jsonObject.toString();
		    		return jb;
		    	}
		    }else {//有旧头像，那么就要先删除服务器中的图片再上传
	        	String realpath=oldhead.substring(28);
		    	int r=fileManager.delete_file(realpath);//删除文件
		    	if(r==0) {
			    	Integer userId=user.getUserId();
			    	User user2=new User();
			    	user2.setUserId(userId);
			    	user2.setHeadSculpture(filePath);
			    	int i=uServiceI.CompleteUserInformation(user2);
			    	if(i>0) {
			    		JsonObject jsonObject=new JsonObject();
			    		jsonObject.addProperty("ecode", "1");
			    		String jb=jsonObject.toString();
			    		return jb;
			    	}else {
			    		JsonObject jsonObject=new JsonObject();
			    		jsonObject.addProperty("ecode", "0");
			    		String jb=jsonObject.toString();
			    		return jb;
			    	}
			    }else {
			    	JsonObject jsonObject=new JsonObject();
		    		jsonObject.addProperty("ecode", "0");
		    		String jb=jsonObject.toString();
		    		return jb;
			    }
	    	}
	    }else {
	    	JsonObject jsonObject=new JsonObject();
    		jsonObject.addProperty("ecode", "0");
    		String jb=jsonObject.toString();
    		return jb;
	    }
	}
	

	/**
	 * @throws Exception 
	 * 
	 * @Title: downloadFile   
	 * @Description:文章的文件下载
	 * @param: @param request
	 * @param: @return      
	 * @return: ResponseEntity<byte[]>      
	 * @throws
	 */
	@RequestMapping("downloadFile")
	public ResponseEntity<byte[]> downloadFile(HttpServletRequest request,HttpSession session) throws Exception{
		try {
			FileManager fileManager=new FileManager("fdfs_client.conf");
			User user=(User) request.getSession().getAttribute("user");
			String username=user.getUserName();
			String filePath=request.getParameter("filePath");
			filePath=filePath.substring(28, filePath.length());
			String substr = filePath.substring(filePath.indexOf("group"));
			String group = substr.split("/")[0];
			String remoteFileName = substr.substring(substr.indexOf("/")+1);
			String specFileName = username + substr.substring(substr.indexOf("."));
			return fileManager.download(group, remoteFileName,specFileName);
		}catch (java.net.SocketTimeoutException e){
			e.printStackTrace();
			return  null;
		}

	}

	    /**
	    　　* @param request session
	    　　* @return  ResponseEntity<byte[]>
	    　　* @author：千夜
	    　　* @date 2019/5/7 19:48
	     　 * @description: TODO:管理员下载文件用
	    　　*/
	@RequestMapping("ManagerDownloadFile")
	public ResponseEntity<byte[]> ManagerDownloadFile(HttpServletRequest request,HttpSession session) throws Exception{
		FileManager fileManager=new FileManager("fdfs_client.conf");
		Manager manager=(Manager) request.getSession().getAttribute("manager");
		String managername=manager.getManagerName();
		String filePath=request.getParameter("filePath");
		filePath=filePath.substring(28, filePath.length());
		String substr = filePath.substring(filePath.indexOf("group"));
		String group = substr.split("/")[0];
		String remoteFileName = substr.substring(substr.indexOf("/")+1);
		String specFileName = managername + substr.substring(substr.indexOf("."));
		return fileManager.download(group, remoteFileName,specFileName);
	}
}
